import {
  // AppThunk,
  useAppDispatch,
  useAppSelector,
} from '@/store/hook'
import { logoutAction } from '@/store/reducers/login'
import {
  patchUserProfileAction,
  UserProfileAction
} from '@/store/reducers/profile'
import {
  Button,
  DatePicker,
  Dialog,
  Input,
  List,
  NavBar,
  TextArea,
  Toast
} from 'antd-mobile'
import dayjs from 'dayjs'
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import InputPop from './component/InputPop/inputPop'
import ListPop, { TListPop } from './component/ListPop/listPop'
import style from './index.module.scss'
export default function UserEdit () {
  // 调用redux
  const dispatch = useAppDispatch()
  const profile = useAppSelector(state => state.profileer.profile)
  useEffect(() => {
    dispatch(UserProfileAction())
  }, [dispatch])

  enum Egender {
    男,
    女
  }

  // 调用自定义hooks调用接口,拿到相应仓库的状态
  // const { profile } = useInitState(UserProfileAction as AppThunk, 'profileer')
  const navigate = useNavigate()

  // 控制时间选择器
  const [visible, setVisible] = useState(false)

  // 控制昵称和简介的弹出层
  const [nickNamePopShow, setNickNamePopShow] = useState(false)
  const [synopsisPopShow, setSynopsisPopShow] = useState(false)

  // 控制昵称和简介的输入框
  const [value, setValue] = useState({
    name: '',
    intro: ''
  })
  useEffect(() => {
    setValue({
      name: profile.name,
      intro: profile.intro || '未填写'
    })
  }, [profile])

  // 修改昵称
  const patchNameSubmit = async () => {
    if (profile.name !== value.name) {
      await dispatch(patchUserProfileAction({ name: value.name }))
      Toast.show({
        icon: 'success',
        afterClose: () => {
          setNickNamePopShow(false)
        },
        content: '修改成功'
      })
    } else {
      setNickNamePopShow(false)
    }
  }

  // 修改简介
  const patchIntroSubmit = async () => {
    if (profile.intro !== value.intro) {
      await dispatch(patchUserProfileAction({ intro: value.intro }))
      Toast.show({
        icon: 'success',
        afterClose: () => setSynopsisPopShow(false),
        content: '修改成功'
      })
    } else {
      setSynopsisPopShow(false)
    }
  }

  // 控制性别和头像的弹出层
  const [listPopShow, setListPopShow] = useState(false)
  const [listType, setListType] = useState<TListPop['type']>('photo')

  // 点击性别和头像
  const showList = (type: TListPop['type']) => {
    setListType(type)
    setListPopShow(true)
  }

  // 更换生日
  const onConfirm = async (val: Date) => {
    const birthday = dayjs(val).format('YYYY-MM-DD')
    // 如果没修改, 退出
    if (profile.birthday === birthday) return
    await dispatch(patchUserProfileAction({ birthday: birthday }))
    Toast.show({
      icon: 'success',
      afterClose: () => setVisible(false),
      content: '修改成功'
    })
  }

  // 退出登陆
  const logout = async () => {
    const result = await Dialog.confirm({
      content: '确认登出吗'
    })
    if (result) {
      await dispatch(logoutAction())
      navigate('/home', { replace: true })
    } else {
    }
  }

  return (
    <div className={style.root}>
      <div className='content'>
        <NavBar onBack={() => navigate('/home/profile')}>个人信息</NavBar>
        <div className='wrapper'>
          {/* 列表上半部分 */}
          <List className='profile-list'>
            <List.Item
              onClick={() => showList('photo')}
              clickable
              arrow
              extra={
                <span className='avatar-wrapper'>
                  <img width={24} height={24} src={profile.photo} alt='' />
                </span>
              }
            >
              头像
            </List.Item>
            <List.Item
              onClick={() => setNickNamePopShow(true)}
              clickable
              arrow
              extra={profile.name}
            >
              昵称
            </List.Item>
            <List.Item
              onClick={() => setSynopsisPopShow(true)}
              clickable
              arrow
              extra={profile.intro || '未填写'}
            >
              简介
            </List.Item>
          </List>
          {/* 列表下半部分 */}
          <List className='profile-list'>
            <List.Item
              onClick={() => showList('gender')}
              clickable
              arrow
              extra={Egender[profile.gender!]}
            >
              性别
            </List.Item>
            <List.Item
              onClick={() => setVisible(true)}
              arrow
              extra={profile.birthday}
            >
              生日
            </List.Item>
          </List>
        </div>
      </div>
      <div className='logout'>
        <Button className='btn' onClick={logout}>
          退出登录
        </Button>
      </div>

      {/* 昵称的弹出层 */}
      <InputPop
        visible={nickNamePopShow}
        close={() => {
          setNickNamePopShow(false)
          setValue(value => ({ ...value, name: profile.name }))
        }}
        submit={patchNameSubmit}
        title='编辑昵称'
      >
        <Input
          onChange={e => setValue(value => ({ ...value, name: e }))}
          placeholder='请输入内容'
          value={value.name}
        />
      </InputPop>

      {/* 简介的弹出层 */}
      <InputPop
        visible={synopsisPopShow}
        close={() => {
          setSynopsisPopShow(false)
          setValue(value => ({ ...value, intro: profile.intro || '未填写' }))
        }}
        submit={patchIntroSubmit}
        title='编辑简介'
      >
        <TextArea
          onChange={e => setValue(value => ({ ...value, intro: e }))}
          value={value.intro || '未填写'}
          maxLength={50}
          showCount
        />
      </InputPop>

      {/* 性别和头像的弹出层 */}
      <ListPop
        visible={listPopShow}
        close={() => setListPopShow(false)}
        type={listType}
      />
      {/* 生日 */}
      <DatePicker
        title='生日'
        visible={visible}
        onClose={() => {
          setVisible(false)
        }}
        onCancel={() => setVisible(false)}
        max={new Date()}
        min={new Date('1970-01-01')}
        onConfirm={val => onConfirm(val)}
        value={new Date(profile.birthday)}
      />
    </div>
  )
}
